import express from "express";
import cors from "cors";
import bodyParser from "body-parser";
import path from "path";
import fs from "fs";
import { fileURLToPath } from "url";

import config from "./config/index.js";
import apiRoutes from "./routes/api.js";
import uploadRoutes from "./routes/upload.js";
import pluginRoutes from "./routes/plugin.js";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 创建应用实例
const app = express();

// 创建临时文件目录
const tempDir = path.join(__dirname, "temp");
if (!fs.existsSync(tempDir)) {
  fs.mkdirSync(tempDir);
}

// 中间件设置
app.use(cors());
app.use(express.json());
app.use(bodyParser.json({ limit: "1mb" }));
app.options("*", cors());

// 路由设置
app.use("/v1", apiRoutes);
app.use("/upload", uploadRoutes);
app.use("/plugin", pluginRoutes);

// 健康检查
app.get("/health", (req, res) => {
  res.json({ status: "ok" });
});

// 启动服务
app.listen(config.port, () => {
  console.log(`Server is listening at http://localhost:${config.port}`);
});
